package com.snail.common.datasource.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.snail.common.core.constant.CommonConstants;
import com.snail.common.security.utils.SecurityUtils;
import com.snail.system.api.model.LoginUser;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @Description: 自动填充字段策略
 * @Author: Snail
 * @CreateDate: 2022/7/8 10:43
 * @Version: V1.0
 */
@Component
@ConditionalOnProperty(name = "snail.mybatisPlus.strictFill",havingValue = "true")
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        this.strictInsertFill(metaObject, "delFlag", String.class, CommonConstants.DELETE_NO);
        this.strictInsertFill(metaObject, "tenantId", String.class, SecurityUtils.getTenantId());
        this.strictInsertFill(metaObject, "createUserId", String.class,  loginUser.getSysUser().getUserId());
        this.strictInsertFill(metaObject, "createUserName", String.class, loginUser.getSysUser().getNickName());
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "deptId", String.class, loginUser.getSysDept().getDeptId());
        this.strictInsertFill(metaObject, "deptName", String.class, loginUser.getSysDept().getDeptName());
        this.strictInsertFill(metaObject, "deptFullId", String.class, loginUser.getSysDept().getDeptFullId());
        this.strictInsertFill(metaObject, "deptFullName", String.class, loginUser.getSysDept().getDeptFullName());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        this.strictUpdateFill(metaObject, "updateUserId", String.class,  loginUser.getSysUser().getUserId());
        this.strictUpdateFill(metaObject, "updateUserName", String.class, loginUser.getSysUser().getNickName());
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
    }

}
